package com.daily.pump.dialog;

import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.daily.pump.R;
import com.daily.pump.adapter.ScanResultWifiListAdapter;
import com.daily.pump.constants.ExtraConstants;
import com.daily.pump.model.Device;
import com.daily.pump.model.SimpleWifiBean;
import com.daily.pump.utils.ScanResultListener;
import com.daily.pump.utils.WifiAutoConnectManager;
import com.daily.pump.utils.WifiHelper;
import com.daily.pump.utils.WifiUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xunxi.mimi.utils.LogUtil;
import com.xunxi.mimi.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * Desc:我的-设置视频聊天价格
 * <p>
 * Author: [李豫]
 * Date: 2018-08-02
 * Copyright: Copyright (c) 2010-2018
 * Updater:
 * Update Time:
 * Update Comments:
 */
public class ScanResultNextDialog extends DialogFragment implements ScanResultListener {

    private ScanDialogListener mScanDialogListener;

    private SmartRefreshLayout mRefreshLayout;

    private EditText mNameEt;

    private ProgressBar mProgressBar;

    private WifiHelper wifiHelper;

    private SimpleWifiBean mScanResult;

    private String mDeviceName;

    private Device mSelectDevice;

    private ScanResultWifiListAdapter mListAdapter;

    public void setScanDialogListener(ScanDialogListener listener) {
        this.mScanDialogListener = listener;
    }

    public static ScanResultNextDialog newInstance(Device device) {
        ScanResultNextDialog scanResultNextDialog = new ScanResultNextDialog();
        Bundle bundle = new Bundle();
        bundle.putParcelable(ExtraConstants.DEVICE_NAME, device);
        scanResultNextDialog.setArguments(bundle);
        return scanResultNextDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.customDialog);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dismissAllowingStateLoss();
                if (mScanDialogListener != null) {
                    mScanDialogListener.onDismiss();
                }
            }
        });
        Window window = getDialog().getWindow();
        window.setGravity(Gravity.CENTER);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View dialogView = inflater.inflate(R.layout.dialog_scan_result_next, container, false);
        initData(dialogView);
        return dialogView;
    }

    private void initData(View dialogView) {
        mNameEt = dialogView.findViewById(R.id.name_et);
        mRefreshLayout = dialogView.findViewById(R.id.refresh_layout);
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                startScan();
            }
        });
        RecyclerView historyRv = dialogView.findViewById(R.id.history_rv);
        historyRv.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mListAdapter = new ScanResultWifiListAdapter(getActivity());
        mListAdapter.setWifiListAdapterListener(new ScanResultWifiListAdapter.WifiListAdapterListener() {
            @Override
            public void onItemClick(SimpleWifiBean simpleWifiBean, int position) {
                mScanResult = mListAdapter.setSelect(position);
            }
        });
        historyRv.setAdapter(mListAdapter);
        mProgressBar = dialogView.findViewById(R.id.progress);
        dialogView.findViewById(R.id.next_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNext();
            }
        });

        Bundle bundle = getArguments();
        if (bundle != null) {
            mSelectDevice = bundle.getParcelable(ExtraConstants.DEVICE_NAME);
            if (mSelectDevice != null) {
                String name = mSelectDevice.deviceName;
                if (!TextUtils.isEmpty(name)) {
                    mNameEt.setText(name);
                    mNameEt.setSelection(name.length());
                }
            }
        }

        mRefreshLayout.autoRefresh();
    }


    private void startScan() {
        if (wifiHelper == null) {
            wifiHelper = new WifiHelper(this, this);
        }
        wifiHelper.startScan();
    }

    private void onNext() {
        mDeviceName = mNameEt.getText().toString().trim();
        if (TextUtils.isEmpty(mDeviceName)) {
            ToastUtil.show(getActivity(), "please input device name!");
            return;
        }

        if (mScanResult == null) {
            ToastUtil.show(getActivity(), "please select connect device");
            return;
        }
        boolean connectTargetWifi = WifiUtil.connectTargetWifi(getActivity(), mScanResult);
        if (connectTargetWifi) {
            mProgressBar.setVisibility(View.VISIBLE);

            if (mScanDialogListener != null) {
                mScanDialogListener.onTurnLogin(mScanResult, mDeviceName);
            }
        } else {
            ToastUtil.show(getActivity(), "please check wifi connect");
        }
    }

    public void show(FragmentManager manager) {
        if (!isShowing()) {
            show(manager, ScanResultNextDialog.class.getSimpleName());
        }
    }

    public boolean isShowing() {
        if (getDialog() != null && getDialog().isShowing()) {
            return true;
        }
        return false;
    }

    public Device getSelectDevice() {
        return mSelectDevice;
    }

    @Override
    public void resultSuc(List<ScanResult> list, boolean isLastTime) {
        mRefreshLayout.finishRefresh();
        mListAdapter.setDataSource(filterWifi(list));
        mListAdapter.notifyDataSetChanged();
    }

    private List<SimpleWifiBean> filterWifi(List<ScanResult> list) {
        List<SimpleWifiBean> wifiResults = new ArrayList<>();
        for (ScanResult scanResult : list) {
            WifiAutoConnectManager.WifiCipherType wifiCipher = WifiUtil.getWifiCipher(scanResult.capabilities);
            if (!TextUtils.isEmpty(scanResult.SSID) && scanResult.SSID.startsWith("AI-") && WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS.equals(wifiCipher)) {
                SimpleWifiBean simpleWifiBean = new SimpleWifiBean();
                simpleWifiBean.wifiName = scanResult.SSID;
                simpleWifiBean.capabilities = scanResult.capabilities;
                simpleWifiBean.level = WifiUtil.getLevel(scanResult.level) + "";
                wifiResults.add(simpleWifiBean);
            }
        }
        return wifiResults;
    }

    @Override
    public void filterFailure() {

    }

    @Override
    public void connectedWifiCallback(WifiInfo info) {
        LogUtil.error(ScanResultNextDialog.class, "connectedWifiCallback" + info.getSSID());
    }

    public void hideProgress() {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    public interface ScanDialogListener {
        void onTurnLogin(SimpleWifiBean simpleWifiBean, String deviceName);

        void onDismiss();
    }
}

